<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="客户" prop="customerId">
        <el-select
          v-model="queryParams.customerId"
          class="!w-200px"
          filterable
          clearable
          lable-key="name"
          placeholder="请选择客户"
          value-key="id"
          @keyup.enter="handleQuery"
        >
          <el-option
            v-for="item in customerList"
            :key="item.id"
            :label="item.name"
            :value="item.id!"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="统计月份" prop="date">
        <el-date-picker
          v-model="queryParams.date"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="monthrange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="营业状态" prop="businessStatus">
        <el-select
          v-model="queryParams.businessStatus"
          placeholder="请选择营业状态"
          clearable
          class="!w-180px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CRM_BUSINESS_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="行业类别" prop="industryCategory">
        <el-select
          v-model="queryParams.industryCategory"
          placeholder="请选择行业类别"
          clearable
          class="!w-180px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CRM_INDUSTRY_CATEGORY)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item class="absolute right-0">
        <el-popover
          :visible="showPopover"
          persistent
          :width="600"
          :show-arrow="false"
          placement="bottom-end"
        >
          <template #reference>
            <el-button v-hasPermi="['crm:operation:query']" @click="showPopover = !showPopover">
              <Icon class="mr-5px" icon="ep:filter" /> 高级筛选
            </el-button>
          </template>

          <el-form-item>
            <el-select placeholder="添加查询条件" @change="addConditions" multiple>
              <el-option
                v-for="item in conditions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
          <div class="popover-content">
            <el-form-item v-for="index in queryParams.condition.length" :key="index">
              <el-select
                v-model="queryParams.condition[index - 1].cond"
                class="!w-230px"
                @change="onChangeCond"
              >
                <el-option
                  v-for="cond in conditions"
                  :key="cond.value"
                  :label="cond.label"
                  :value="cond.value"
                  :disabled="cond.disabled"
                />
              </el-select>
              <el-select
                v-if="!queryParams.condition[index - 1].cond.startsWith('is')"
                v-model="queryParams.condition[index - 1].comp"
                class="!w-100px"
              >
                <el-option
                  v-for="comp in compares"
                  :key="comp.value"
                  :label="comp.label"
                  :value="comp.value"
                />
              </el-select>
              <el-select
                v-if="queryParams.condition[index - 1].cond.startsWith('is')"
                v-model="queryParams.condition[index - 1].comp"
                class="!w-100px"
              >
                <el-option
                  v-for="bool in boolean"
                  :key="bool.value"
                  :label="bool.label"
                  :value="bool.value"
                />
              </el-select>
              <el-input-number
                v-if="!queryParams.condition[index - 1].cond.startsWith('is')"
                v-model="queryParams.condition[index - 1].input"
                clearable
                style="width: 170px"
                :precision="2"
                :min="0"
                disabled-scientific
              />
              <el-button
                type="danger"
                :icon="Delete"
                circle
                class="ml-10px"
                size="small"
                plain
                @click="onDelCondition(index - 1)"
              />
            </el-form-item>
          </div>
          <el-form-item class="font-bold" label-position="top">
            <div class="flex justify-start w-full">
              <el-button type="primary" @click="handleQuery">搜索</el-button>
              <el-button @click="resetQuery">清空</el-button>
              <el-button @click="showPopover = false">取消</el-button>
              <el-button @click="delAllCondition" type="danger" plain>删除全部</el-button>
            </div>
          </el-form-item>
        </el-popover>
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['crm:operation:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['crm:operation:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          v-hasPermi="['crm:operation:submit']"
          type="primary"
          plain
          @click="handleReCreate()"
        >
          <Icon class="mr-5px" icon="ep:refresh" />
          重新发起
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
    >
      <el-table-column type="selection" />
      <el-table-column align="center" fixed="left" label="客户" prop="customerName" width="300px">
        <template #default="scope">
          <el-link
            :underline="false"
            type="primary"
            @click="openCustomerDetail(scope.row.customerId)"
          >
            {{ scope.row.customerName }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column
        label="统计月份"
        align="center"
        prop="date"
        :formatter="dateFormatter3"
        width="120px"
        fixed="left"
      />
      <el-table-column label="运营经理" align="center" prop="operationManagerName" />
      <el-table-column label="营业状态" align="center" prop="businessStatus" width="120px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CRM_BUSINESS_STATUS" :value="scope.row.businessStatus" />
        </template>
      </el-table-column>
      <el-table-column label="细分行业" align="center" prop="industryCategory" width="180px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CRM_INDUSTRY_CATEGORY" :value="scope.row.industryCategory" />
        </template>
      </el-table-column>
      <el-table-column
        label="设备抵押情况"
        align="center"
        prop="mortgageEquipmentSituation"
        width="120px"
      >
        <template #default="scope">
          <dict-tag
            :type="DICT_TYPE.CRM_MORTGAGE_EQUIPMENT_SITUATION"
            :value="scope.row.mortgageEquipmentSituation"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="设备抵押估值（万元）"
        align="center"
        prop="equipmentMortgageValuation"
        width="110px"
      />
      <el-table-column
        label="个人担保情况"
        align="center"
        prop="personalGuaranteeSituation"
        width="110px"
      >
        <template #default="scope">
          <dict-tag
            :type="DICT_TYPE.CRM_PERSONAL_GUARANTEE_SITUATION"
            :value="scope.row.personalGuaranteeSituation"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="其他经营概况描述"
        align="center"
        prop="otherSituations"
        width="300px"
      />
      <el-table-column label="租金配套欠费（万元）" align="center" prop="rent" />
      <el-table-column label="供应链欠费（万元）" align="center" prop="supplyChain" />
      <el-table-column label="园区总欠费（万元）" align="center" prop="allFee" />
      <el-table-column label="欠薪金额（万元）" align="center" prop="backPayAmount" />
      <el-table-column label="银行贷款（万元）" align="center" prop="loan" />
      <el-table-column label="其它社会债务（万元）" align="center" prop="otherDebts" />
      <el-table-column label="总负债估算（万元）" align="center" prop="allDebt" />
      <el-table-column label="产值（万元）" align="center" prop="outputAmount" />
      <el-table-column label="主要客户货款回笼周期（月）" align="center" prop="paymentCycle" />
      <el-table-column label="现有员工人数" align="center" prop="totalEmp" />
      <el-table-column label="缺工人数" align="center" prop="shortageEmp" />
      <el-table-column label="是否有集体裁员计划" align="center" prop="isLayoffPlan">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.isLayoffPlan" />
        </template>
      </el-table-column>
      <el-table-column label="计划裁员人数" align="center" prop="layoffs" />
      <el-table-column label="是否有降薪计划" align="center" prop="isSalaryReductionPlan">
        <template #default="scope">
          <dict-tag
            :type="DICT_TYPE.INFRA_BOOLEAN_STRING"
            :value="scope.row.isSalaryReductionPlan"
          />
        </template>
      </el-table-column>
      <el-table-column label="计划降薪幅度（%）" align="center" prop="salaryReductionRange" />
      <el-table-column label="是否欠薪" align="center" prop="isBackPay">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.isBackPay" />
        </template>
      </el-table-column>
      <el-table-column label="欠薪月数" align="center" prop="backPayDuration" />
      <el-table-column label="欠薪人数" align="center" prop="backPay" />
      <el-table-column label="出口订单占比（%）" align="center" prop="exportOrderRate" />
      <el-table-column label="内销订单占比（%）" align="center" prop="domesticOrderRate" />
      <el-table-column label="产能利用率（%）" align="center" prop="capacityRate" />
      <el-table-column
        label="当月订单饱和度（%）"
        align="center"
        prop="monthlyOrderSaturationRate"
      />
      <el-table-column label="开工天数" align="center" prop="workingDays" />
      <el-table-column label="开工时数" align="center" prop="workingHours" />
      <el-table-column label="操作" align="center" fixed="right" min-width="300">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['crm:operation:update']"
          >
            编辑
          </el-button>
          <el-button
            v-if="scope.row.auditStatus === 0"
            v-hasPermi="['crm:operation:submit']"
            link
            type="primary"
            @click="handleSubmit(scope.row)"
          >
            提交审核
          </el-button>
          <el-button
            v-else
            link
            v-hasPermi="['crm:operation:update']"
            type="primary"
            @click="handleProcessDetail(scope.row)"
          >
            查看审批
          </el-button>
          <el-button
            v-show="
              scope.row.auditStatus === 20 ||
              scope.row.auditStatus === 30 ||
              scope.row.auditStatus === 40 ||
              scope.row.auditStatus === 4
            "
            link
            v-hasPermi="['crm:operation:submit']"
            type="primary"
            @click="handleReCreate(scope.row)"
          >
            重新发起
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['crm:operation:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <OperationForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter3 } from '@/utils/formatTime'
import * as CustomerApi from '@/api/crm/customer'
import download from '@/utils/download'
import { OperationApi, OperationVO } from '@/api/crm/operation'
import OperationForm from './OperationForm.vue'
import { Delete } from '@element-plus/icons-vue'
import { log } from 'node:console'

/** CRM 运营信息 列表 */
defineOptions({ name: 'Operation' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<OperationVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  customerId: undefined,
  date: [],
  operationManager: undefined,
  operationManagerName: undefined,
  businessStatus: undefined,
  industryCategory: undefined,
  otherSituations: undefined,
  createTime: [],
  condition: [] as conditionType[]
})

type conditionType = { cond: string; comp: string; input: string }
const compares = [
  {
    label: '等于',
    value: 'eq'
  },
  {
    label: '不等于',
    value: 'ne'
  },
  {
    label: '大于',
    value: 'gt'
  },
  {
    label: '大于等于',
    value: 'ge'
  },
  {
    label: '小于',
    value: 'lt'
  },
  {
    label: '小于等于',
    value: 'le'
  }
]
const boolean = [
  { label: '是', value: '1' },
  { label: '否', value: '0' }
]
const conditions = ref([
  { label: '租金配套欠费（万元）', disabled: false, value: 'rent' },
  { label: '供应链欠费（万元）', disabled: false, value: 'supplyChain' },
  { label: '园区总欠费（万元）', disabled: false, value: 'allFee' },
  { label: '欠薪金额（万元）', disabled: false, value: 'backPayAmount' },
  { label: '银行贷款（万元）', disabled: false, value: 'loan' },
  { label: '其它社会债务（万元）', disabled: false, value: 'otherDebts' },
  { label: '总负债估算（万元）', disabled: false, value: 'allDebt' },
  { label: '产值（万元）', disabled: false, value: 'outputAmount' },
  { label: '主要客户货款回笼周期（月）', disabled: false, value: 'paymentCycle' },
  { label: '现有员工人数', disabled: false, value: 'totalEmp' },
  { label: '缺工人数', disabled: false, value: 'shortageEmp' },
  { label: '是否有集体裁员计划', disabled: false, value: 'isLayoffPlan' },
  { label: '计划裁员人数', disabled: false, value: 'layoffs' },
  { label: '是否有降薪计划', disabled: false, value: 'isSalaryReductionPlan' },
  { label: '计划降薪幅度（%）', disabled: false, value: 'salaryReductionRange' },
  { label: '是否欠薪', disabled: false, value: 'isBackPay' },
  { label: '欠薪月数', disabled: false, value: 'backPayDuration' },
  { label: '欠薪人数', disabled: false, value: 'backPay' },
  { label: '出口订单占比（%）', disabled: false, value: 'exportOrderRate' },
  { label: '内销订单占比（%）', disabled: false, value: 'domesticOrderRate' },
  { label: '产能利用率（%）', disabled: false, value: 'capacityRate' },
  { label: '当月订单饱和度（%）', disabled: false, value: 'monthlyOrderSaturationRate' },
  { label: '开工天数', disabled: false, value: 'workingDays' },
  { label: '开工工时数', disabled: false, value: 'workingHours' }
])

const queryFormRef = ref() // 搜索的表单
const tableRef = ref()
const exportLoading = ref(false) // 导出的加载中
const customerList = ref<CustomerApi.CustomerVO[]>([]) // 客户列表
const { push } = useRouter()
const showPopover = ref(false)

/** 打开客户详情 */
const openCustomerDetail = (id: number) => {
  push({ name: 'CrmCustomerDetail', params: { id } })
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await OperationApi.getOperationPage(queryParams.value)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.value.condition.forEach((item) => {
    item.input = ''
    item.comp = ''
  })
  handleQuery()
}

/** 提交审核 */
const handleSubmit = async (row: OperationVO) => {
  await message.confirm(`您确定提交审核吗？`)
  await OperationApi.submit(Array.of(row.id), false)
  message.success('提交审核成功！')
  await getList()
}
/** 重新发起 */
const handleReCreate = async (row?: OperationVO) => {
  if (!tableRef.value) {
    return message.warning('表格未加载完成，请稍后再试')
  }
  const rows = tableRef.value.getSelectionRows()
  if (rows.length === 0 && row?.processInstanceId == undefined) {
    return message.warning('请选择要再次提交的客户！')
  }
  if (row?.processInstanceId != undefined) {
    await message.confirm(`您确定再次提交【${row?.customerName}】运营信息审核吗？`)
    await OperationApi.submit(Array.of(row?.id), true)
    message.success('再次提交成功！')
    await getList()
    return
  }
  await message.confirm(
    `您确定再次提交【${rows.map((row: OperationVO) => row.customerName).join(',')}】运营信息吗？`
  )
  await OperationApi.submit(Array.of(rows.map((row: OperationVO) => row.id)), true)
  message.success('再次提交成功！')
  await getList()
}
/** 查看审批详情 */
const handleProcessDetail = async (row: CustomerApi.CustomerVO) => {
  push({ name: 'BpmProcessInstanceDetail', query: { id: row.processInstanceId } })
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}
/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await OperationApi.deleteOperation(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const exportParams = {
      pageNo: 1,
      pageSize: 10,
      customerId: queryParams.value.customerId,
      date: queryParams.value.date,
      operationManager: queryParams.value.operationManager,
      operationManagerName: queryParams.value.operationManagerName,
      businessStatus: queryParams.value.businessStatus,
      industryCategory: queryParams.value.industryCategory,
      otherSituations: queryParams.value.otherSituations,
      createTime: queryParams.value.createTime,
      condition: queryParams.value.condition
    }
    const data = await OperationApi.exportOperation(exportParams)
    download.excel(data, 'CRM 运营信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const addConditions = (value: any[]) => {
  conditions.value.forEach((item) => {
    if (item.value == value[0]) {
      item.disabled = true
      queryParams.value.condition.push({ cond: item.value, comp: '', input: '' })
    }
  })
}
const onChangeCond = () => {
  const conds = queryParams.value.condition.map((item) => item.cond)
  conditions.value.forEach((item2) => {
    if (conds.includes(item2.value)) {
      item2.disabled = true
    } else {
      item2.disabled = false
    }
  })
}

const onDelCondition = (index: number) => {
  conditions.value.forEach((item2) => {
    if (item2.value == queryParams.value.condition[index].cond) {
      item2.disabled = false
    }
  })
  queryParams.value.condition = queryParams.value.condition.filter(
    (item) => item.cond != queryParams.value.condition[index].cond
  )
}
const delAllCondition = () => {
  queryParams.value.condition = []
  conditions.value.forEach((item) => (item.disabled = false))
}

/** 初始化 **/
onMounted(async () => {
  await getList()
  customerList.value = await CustomerApi.getCustomerSimpleList()
})
</script>
<style lang="scss" scoped>
.popover-content {
  max-height: 400px; /* 设置最大高度 */
  overflow-y: auto; /* 显示垂直滚动条 */
  padding: 10px;
}
</style>
